/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trunk.view;

//Import's

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;

//import trunk.model.calendar.AppPreferences;
//import trunk.model.calendar.EventInstance;
//import trunk.model.calendar.Calendar;
//import trunk.model.calendar.EventInstance;
//import trunk.model.calendar.Repository;
//import trunk.model.calendar.RepositoryChangeListener;
//import us.k5n.ical.Constants;
import trunk.control.UsuarioControlador;
import trunk.model.BancoDeClientes;
import trunk.model.BancoDeCompromissos;
import trunk.model.BancoDeConvidados;
import trunk.model.TipoStatus;
import trunk.model.calendar.CalendarDataRepository;
import trunk.model.calendar.Event;
import trunk.model.calendar.EventInstance;
//import trunk.model.calendar.Event;

/**
 *
 * @author Ycaro_2
 */



@SuppressWarnings("serial")
public class ViewEcompCalendar extends JFrame implements CalendarDataRepository,
CalendarPanelSelectionListener{

	static ClassLoader cl = null;
	JFrame parent;
	EventViewPanel eventViewPanel;
	JButton newButton;
	JButton editButton;
	JButton deleteButton;
	JButton BatePapoButton;
	JButton ConferenciaButton;
	JLabel messageArea;
	//Repository dataRepository;
	CalendarPanel calendarPanel;
	JSplitPane horizontalSplit = null, leftVerticalSplit = null;
	JPanel usuarios;
	JMenuItem logout;
	JMenuItem encerrarConta;
	JMenuItem sair;
	//JListWithCheckBoxes calendarJList;
	String searchText = null;
	@SuppressWarnings("unused")
	private static File lastExportDirectory = null;
	File dataDir = null;
	static final String MENU_CALENDAR_EDIT = "Edit Calendar...";
	static final String MENU_CALENDAR_REFRESH = "Refresh Calendar";
	static final String MENU_CALENDAR_DELETE = "Delete Calendar";
	static final String MENU_CALENDAR_ADD_EVENT = "Add Event...";
	static final String MENU_CALENDAR_VIEW_ERRORS = "View Errors/Warnings...";
	static final String ADD_EVENT_LABEL = "Novo Evento";
	static final String EDIT_EVENT_LABEL = "Editar Evento";
	static final String DELETE_EVENT_LABEL = "Apagar Evento";
	static final String BatePapo_EVENT_LABEL = "Bate-Papo";
	static final String Conf_EVENT_LABEL = "Videoconferência";
	static final String LARGER_FONT_LABEL = "Aumentar";
	static final String SMALLER_FONT_LABEL = "Diminuir";
	int oldOffset = 0;
	private UsuarioControlador controlador;
	private BancoDeCompromissos compromissos;
	private BancoDeClientes bancoClientes; //KARINE
	private JTable tabelaClientes; //KARINE
	private JScrollPane tabelaScroll;
	private TableModelClientes clienteModel;//KARINE
	private EventInstance eventSelected;
	//AppPreferences prefs;

	//Construtor da Classe
	public ViewEcompCalendar(BancoDeClientes clientes,
			BancoDeCompromissos compromissos, UsuarioControlador controlador){
		super("EcompCalendar");
		this.parent = this;
		this.controlador = controlador;
		this.compromissos = compromissos;
		this.bancoClientes = clientes;
		System.out.println("compromissos:"+this.compromissos);
		//Definições da dimensão da janela       
		setSize (800, 600);
		this.setLocationRelativeTo(null);
		setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
		Container contentPane = getContentPane ();


		/**Load do dados
		 *
		 *
		 */


		//Criação da barra de menu        
		setJMenuBar ( createMenu () );
		contentPane.setLayout ( new BorderLayout () );

		usuarios = new JPanel();
		clienteModel = new TableModelClientes(bancoClientes);
		tabelaClientes = new JTable();
		tabelaClientes.setAutoCreateRowSorter(true);
		tabelaClientes.setModel(clienteModel);
		tabelaScroll = new JScrollPane(tabelaClientes);

		//Tela de detalhes do Evento
		eventViewPanel = new EventViewPanel (controlador);
		eventViewPanel.setBorder ( BorderFactory
				.createTitledBorder ( "Detalhes do Evento" ) );

		leftVerticalSplit = new JSplitPane ( JSplitPane.VERTICAL_SPLIT, tabelaScroll,
				eventViewPanel );
		leftVerticalSplit.setOneTouchExpandable ( true );
		leftVerticalSplit.setDividerLocation (300);

		//Barra de Ferramentas                
		JPanel rightPanel = new JPanel ();
		rightPanel.setLayout ( new BorderLayout () );
		rightPanel.add ( createToolBar (), BorderLayout.NORTH );


		//Carregando na tela o calendario de eventos
		calendarPanel = new CalendarPanel(this);
		calendarPanel.addSelectionListener (this);
		calendarPanel.setShowTime ( false );
		rightPanel.add ( calendarPanel, BorderLayout.CENTER );


		horizontalSplit = new JSplitPane ( JSplitPane.HORIZONTAL_SPLIT,
				leftVerticalSplit, rightPanel );
		horizontalSplit.setOneTouchExpandable ( true );
		horizontalSplit.setDividerLocation ( 200 );
		//horizontalSplit.addPropertyChangeListener ( this );

		this.add ( horizontalSplit, BorderLayout.CENTER );

		//this.addComponentListener ( this );
		this.setVisible ( true );
		//prefs = new AppPreferences();
	}    


	public void paint ( Graphics g ) {
		Font currentFont = g.getFont ();
		Font newFont = new Font ( currentFont.getFamily (), currentFont
				.getStyle (), currentFont.getSize () + 0 );
		//eventViewPanel.setAllFonts ( newFont );
		calendarPanel.setFont ( newFont );
		super.paint ( g );
	}

	public void setMessage ( String msg ) {
		this.messageArea.setText ( msg );
	}

	//Metodo da Barra de Menu    
	public JMenuBar createMenu () {
		JMenuBar bar = new JMenuBar ();

		//Botões da Barra de Menu

		//Barra Usuário
		JMenu fileMenu = new JMenu ( "Usuário" );

		// Botão Logout
		logout = new JMenuItem ( "Logout" );
		logout.addActionListener (controlador);
		fileMenu.add ( logout );
		bar.add ( fileMenu );         

		fileMenu.addSeparator ();

		//Botão SAIR

		sair = new JMenuItem ( "Sair" );
		sair.addActionListener(controlador);
		fileMenu.add (sair);
		bar.add ( fileMenu );


		fileMenu.addSeparator ();

		//BotãoEncerrar minha Conta
		encerrarConta = new JMenuItem ( "Encerrar Minha Conta" );
		encerrarConta.addActionListener(controlador);
		fileMenu.add (encerrarConta);
		bar.add ( fileMenu );







		// Adiciona na barra botão de Ajuda no fim (Foi criado para teste mesmo)
		//bar.add ( Box.createHorizontalGlue () );

		JMenu helpMenu = new JMenu ( "Ajuda" );

		JMenuItem ajuda = new JMenuItem ( "Sobre..." );
		ajuda.setAccelerator ( KeyStroke.getKeyStroke ( 'A', Toolkit
				.getDefaultToolkit ().getMenuShortcutKeyMask () ) );
		ajuda.addActionListener ( new ActionListener () {
			public void actionPerformed ( ActionEvent event ) {
				JOptionPane.showMessageDialog(parent, "Feito por alguem");
			}
		} );
		helpMenu.add ( ajuda );

		bar.add ( helpMenu );

		return bar;
	}


	JToolBar createToolBar () {
		JToolBar toolbar = new JToolBar ();

		newButton = new JButton (ADD_EVENT_LABEL);
		newButton.setVerticalTextPosition ( JButton.BOTTOM );
		newButton.setHorizontalTextPosition ( JButton.CENTER );
		newButton.setActionCommand ( "Novo Evento" );
		newButton.setToolTipText ( "Adiciona novo Evento" );

		newButton.addActionListener (controlador);
		toolbar.add ( newButton );

		editButton = new JButton (EDIT_EVENT_LABEL);
		editButton.setVerticalTextPosition ( JButton.BOTTOM );
		editButton.setHorizontalTextPosition ( JButton.CENTER );
		editButton.setActionCommand ( "Editar Eevento" );
		editButton.setToolTipText ( "Edita um Evento" );
		toolbar.add ( editButton );
		editButton.setEnabled(false);

		editButton.addActionListener (controlador);

		deleteButton = new JButton (DELETE_EVENT_LABEL);
		deleteButton.setVerticalTextPosition ( JButton.BOTTOM );
		deleteButton.setHorizontalTextPosition ( JButton.CENTER );
		deleteButton.setActionCommand ( "Deletar Evento" );
		deleteButton.setToolTipText ( "Deletar um Evento" );
		toolbar.add ( deleteButton );
		deleteButton.setEnabled(false);

		deleteButton.addActionListener (controlador);

		//Botão para bate-papo:
		//BatePapoButton

		BatePapoButton = new JButton (BatePapo_EVENT_LABEL);
		BatePapoButton.setVerticalTextPosition ( JButton.BOTTOM );
		BatePapoButton.setHorizontalTextPosition ( JButton.CENTER );
		BatePapoButton.setActionCommand ( "Deletar Evento" );
		BatePapoButton.setToolTipText ( "Deletar um Evento" );
		toolbar.add (BatePapoButton);
		BatePapoButton.setEnabled(true);
		BatePapoButton.addActionListener (controlador);
		
		ConferenciaButton = new JButton (Conf_EVENT_LABEL);
		ConferenciaButton.setVerticalTextPosition ( JButton.BOTTOM );
		ConferenciaButton.setHorizontalTextPosition ( JButton.CENTER );
		ConferenciaButton.setActionCommand ( "Conf Evento" );
		ConferenciaButton.setToolTipText ( "Iniciar videoconferência" );
		toolbar.add (ConferenciaButton);
		ConferenciaButton.setEnabled(true);
		ConferenciaButton.addActionListener (controlador);

		return toolbar;
	}       



	/*public void saveWindowPreferences () {
		prefs.setMainWindowX ( this.getX () );
		prefs.setMainWindowY ( this.getY () );
		prefs.setMainWindowWidth ( this.getWidth () );
		prefs.setMainWindowHeight ( this.getHeight () );
		prefs.setMainWindowLeftVerticalSplitPosition ( leftVerticalSplit
				.getDividerLocation () );
		prefs.setMainWindowHorizontalSplitPosition ( horizontalSplit
				.getDividerLocation () );
	}*/

	//Sobresquitas exigidas por conta dos Implements    
	/*@Override
	public void componentResized(ComponentEvent ce) {
		saveWindowPreferences ();
	}

	@Override
	public void componentMoved(ComponentEvent ce) {
		saveWindowPreferences ();
	}

	@Override
	public void componentShown(ComponentEvent ce) {        
	}

	@Override
	public void componentHidden(ComponentEvent ce) {
		throw new UnsupportedOperationException("Not supported yet.");
	}*/
	/*
	@Override
	public void propertyChange(PropertyChangeEvent pce) {
		if ( pce.getPropertyName ().equals ( JSplitPane.DIVIDER_LOCATION_PROPERTY ) ) {
			saveWindowPreferences ();
		}
	}

	/*@Override
	public void eventAdded(Event event) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void eventUpdated(Event event) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void eventDeleted(Event event) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void calendarAdded(Calendar c) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void calendarUpdated(Calendar c) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void calendarDeleted(Calendar c) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void displaySettingsChanged() {
		this.calendarPanel.setShowTime ( prefs.getDisplayHourInMonthView () );
		Font oldFont = this.calendarPanel.getFont ();
		Font defaultFont = this.getFont ();
		Font newFont = new Font ( oldFont.getFamily (), oldFont.getStyle (),
				defaultFont.getSize () + prefs.getDisplayFontSize () );
		this.calendarPanel.setFont ( newFont );
		this.dataRepository.rebuild ();
		this.calendarPanel.repaint ();
		this.eventViewPanel.setAllFonts ( newFont );
	}

	@Override
	public void eventSelected(EventInstance ei) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void eventUnselected() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void eventDoubleClicked(EventInstance ei) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void dateDoubleClicked(int i, int i1, int i2) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public void refreshCalendar(Calendar cal) {
		throw new UnsupportedOperationException("Not supported yet.");
	}*/


	public JButton getNewButton() {
		return newButton;
	}


	public JButton getEditButton() {
		return editButton;
	}


	public JButton getDeleteButton() {
		return deleteButton;
	}

	public JButton getBatePapoButton() {

		return BatePapoButton;

	}


	public void setCompromissos(BancoDeCompromissos compromissos){
		this.compromissos = compromissos;
		calendarPanel.repaint();
	}

	public void setBancoDeClientes(BancoDeClientes clientes){
		this.bancoClientes = clientes;
		clienteModel.linhas = bancoClientes.getBancoDeClientes();
		clienteModel.fireTableDataChanged();
	}

	public void setInviteds(BancoDeConvidados convidados){
		eventViewPanel.setInviteds(convidados);
	}

	public void setConfirmarButtonEnable(Boolean enable){
		eventViewPanel.setConfirmarButtonEnable(enable);
	}

	public JMenuItem getLogout(){

		return logout;
	}

	public JMenuItem getEncerrarConta(){

		return encerrarConta;
	}

	public JMenuItem getSair(){

		return sair;
	}


	public EventInstance getEventSelected() {
		return eventSelected;
	}

	public JButton getConfirmarButton(){
		return eventViewPanel.getConfirmarButton();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Vector getEventInstancesForDate(int year, int month, int day) {
		Vector ret  = new Vector();
		if(compromissos!=null){
			for(Event compromisso:compromissos){
				if(compromisso.getDayOfMonth()==day 
						&& compromisso.getMonth()==month
						&& compromisso.getYear()==year)
					ret.add(compromisso);
			}
			return ret;
		} else
			return null;
	}

	@Override
	public void dateDoubleClicked(int arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void eventDoubleClicked(EventInstance arg0) {
		editButton.doClick();
	}

	@Override
	public void eventSelected(EventInstance selectedEvent) {
		editButton.setEnabled(true);
		deleteButton.setEnabled(true);
		eventSelected = selectedEvent;
		eventViewPanel.update(selectedEvent);
		controlador.setUserStatus(TipoStatus.VISUALIZANDO);
	}

	@Override
	public void eventUnselected() {
		editButton.setEnabled(false);
		deleteButton.setEnabled(false);
		eventSelected = null;
		eventViewPanel.update((EventInstance)null);
		controlador.setUserStatus(TipoStatus.ONLINE);
	}


	public JButton getConferenciaButton() {
		return ConferenciaButton;
	}
}
